/*
useEffect(()=>{},arr)
1、arr若为空，则会在组件初始化和更新时执行
2、arr若为空数组[]，则会在组件初始化执行一次
3、arr里面如果包含某数据，则会在初始化和某数据变化时执行
如果想清除副作用，可以在return回调函数中清除
react hooks使用规则
  1、只能在组件顶层使用
  2、不能再组件外部使用
  3、不能在if for 组件内部函数使用
*/

import { createContext, use, useContext, useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { useDispatch } from "react-redux";
import { increment,decrement,incrementByAmount } from "./store/modules/counterStore";
import { getChannels } from "./store/modules/channelStore";
// 创建一个context
const Ctx = createContext();

function A({name}) {
  // 获取redux状态count
  const { count } = useSelector(state => state.counter);
  // 获取redux的dispatch
  const dispatch = useDispatch();

  const msg = "this is A msg";
  const aCtx = useContext(Ctx);
  console.log("这个aCtx:",aCtx);
  useEffect(()=>{
    console.log("执行A组件中的useEffect");
    
  })
  
  return (
    <div>
      {msg},{name}
      <div>
        <button onClick={()=>dispatch(decrement())}>-</button>
        <span>{count}</span>
        <button onClick={()=>dispatch(increment())}>+</button>
        <button onClick={()=>dispatch(incrementByAmount(5))}>+5</button>
      </div>
    </div>
  )
}
function B({onHandleSend}) {
  const msg = "this is B msg";
  const bCtx = useContext(Ctx);
  console.log("这个bCtx:",bCtx);
  // 获取redux的dispatch
  const dispatch = useDispatch();
  // 获取redux状态异步执行channels
  useEffect(()=>{
    console.log("执行B组件中的useEffect");
    dispatch(getChannels());
  },[dispatch])
  return (
    <div>
      {msg}
      <button onClick={()=>onHandleSend(msg)}>将B的数据传递给A</button>
    </div>
  )
}

function App() {
const [name,setName] = useState("");
const appMsg = "this App msg";
  const onHandleSend = (msg)=>{
    console.log(msg);
    setName(msg)
  }
  return (
    <div className="App">
      <Ctx.Provider value={appMsg}>
        <A name={name}></A>
      </Ctx.Provider>      
      <B onHandleSend={onHandleSend}></B>
    </div>
  );
}

export default App;
